<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <!-- <el-form-item label="年份" prop="years">
        <el-date-picker
          v-model="queryParams.years"
          value-format="YYYY"
          type="year"
          placeholder="选择年份"
          clearable
          class="!w-240px"
        />
      </el-form-item> -->
      
      <el-form-item label="时间" prop="monthPicker">
        <el-date-picker
          v-model="queryParams.monthPicker"
          value-format="YYYY-MM"
          type="month"
          placeholder="选择时间"
          clearable
          class="!w-240px"
          @change="handleMonthChange"
        />
      </el-form-item>
      <el-form-item label="员工姓名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入员工姓名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['oa:employee-score:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['oa:employee-score:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>&nbsp;&nbsp;
        <el-upload
          :show-file-list="false"
          :before-upload="beforeImport"
          accept=".xlsx,.xls"
          v-hasPermi="['oa:employee-score:import']"
        >
          <el-button type="warning" plain>
            <Icon icon="ep:upload" class="mr-5px" /> 导入
          </el-button>
        </el-upload>&nbsp;&nbsp;
        
        <el-button type="info" plain @click="downloadTemplate" v-hasPermi="['oa:employee-score:import']">
          <Icon icon="ep:document" class="mr-5px" /> 下载模板
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <!-- <el-table-column label="序号" align="center" prop="id" /> -->
      <el-table-column label="年份" align="center" prop="years" />
      <el-table-column label="月份" align="center" prop="month" />
      <el-table-column label="员工姓名" align="center" prop="userName" />
      <el-table-column label="分配企业总户数" align="center" prop="totalEnterprises" />
      <el-table-column label="小规模户数" align="center" prop="smallScaleEnterprises" />
      <el-table-column label="一般纳税人户数" align="center" prop="generalTaxpayerEnterprises" />
      <el-table-column label="小规模分" align="center" prop="smallScaleScore" />
      <el-table-column label="一般纳税人分" align="center" prop="generalTaxpayerScore" />
      <el-table-column label="简化小规模户数" align="center" prop="simplifiedSmallScale" />
      <el-table-column label="简化一般纳税人户数" align="center" prop="simplifiedGeneralTaxpayer" />
      <el-table-column label="简化小规模分" align="center" prop="simplifiedSmallScaleScore" />
      <el-table-column label="简化一般纳税人分" align="center" prop="simplifiedGeneralTaxpayerScore" />
      <el-table-column label="开票分" align="center" prop="invoiceScore" />
      <el-table-column label="特殊分" align="center" prop="specialScore" />
      <el-table-column label="工龄分" align="center" prop="seniorityScore" />
      <el-table-column label="证书分" align="center" prop="certificateScore" />
      <el-table-column label="收款完成率(%)" align="center" prop="collectionCompletionRate" />
      <el-table-column label="收款扣分" align="center" prop="collectionDeduction" />
      <el-table-column label="投诉扣分" align="center" prop="complaintDeduction" />
      <el-table-column label="流失扣分" align="center" prop="lossDeduction" />
      <el-table-column label="记账扣分" align="center" prop="accountingDeduction" />
      <el-table-column label="其他扣分" align="center" prop="otherDeduction" />
      <el-table-column label="工作绩效考核扣分小计" align="center" prop="performanceDeductionSubtotal" />
      <el-table-column label="负责人给予考核分" align="center" prop="managerAssessmentScore" />
      <el-table-column label="总分值" align="center" prop="totalScore" />
      <el-table-column label="考核工资" align="center" prop="assessmentSalary" />
      <el-table-column label="考核基数" align="center" prop="otherAdjustment" />
      <el-table-column label="状态" align="center" prop="status" width="120">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'warning'">
            {{ scope.row.status === 1 ? '已发布' : '未发布' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remarks" />
      <!-- <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      /> -->
      <el-table-column label="操作" align="center" min-width="180px" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['oa:employee-score:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="success"
            @click="handlePublish(scope.row.id)"
            v-hasPermi="['oa:employee-score:update']"
            v-if="scope.row.status === 0"
          >
            发布
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['oa:employee-score:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <EmployeeScoreForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts"> 
import download from '@/utils/download'
import { EmployeeScoreApi, EmployeeScoreVO } from '@/api/oa/employeescore'
import EmployeeScoreForm from './EmployeeScoreForm.vue'

/** 财务部员工分值考核 列表 */
defineOptions({ name: 'AllEmployeeScore' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<EmployeeScoreVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  years: undefined as string | undefined,
  month: undefined as string | undefined,
  monthPicker: undefined as string | undefined, // 用于界面显示的月份选择器
  userName: undefined,
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
/** 月份选择器变化处理 */
const handleMonthChange = (value: string | null) => {
  if (value) {
    // 拆分年月数据,例如 "2024-03" -> years: "2024", month: "03"
    const parts = value.split('-')
    queryParams.years = parts[0]
    queryParams.month = parts[1]
  } else {
    // 清空时重置年份和月份
    queryParams.years = undefined
    queryParams.month = undefined
  }
}
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await EmployeeScoreApi.getAllEmployeeScorePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await EmployeeScoreApi.deleteEmployeeScore(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 发布按钮操作 */
const handlePublish = async (id: number) => {
  try {
    // 发布的二次确认
    await ElMessageBox.confirm('确认发布该员工分值考核吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    // 发起发布
    await EmployeeScoreApi.publishEmployeeScore(id)
    message.success('发布成功')
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await EmployeeScoreApi.exportEmployeeScore(queryParams)
    download.excel(data, '财税部月度考核.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 导入按钮操作 */
const beforeImport = async (file: File) => {
  try {
    const formData = new FormData()
    formData.append('file', file)
    const result = await EmployeeScoreApi.importEmployeeScore(formData)
    const { createCount = 0, updateCount = 0, skipCount = 0 } = result.data || {}
    message.success(`导入成功：新增 ${createCount} 条，修改 ${updateCount} 条，跳过 ${skipCount} 条`)
    await getList()
  } catch (error: any) {
    message.error('导入失败：' + (error.message || '未知错误'))
  }
  return false // 阻止默认上传行为
}

/** 下载模板按钮操作 */
const downloadTemplate = async () => {
  try {
    const data = await EmployeeScoreApi.downloadImportTemplate()
    download.excel(data, '财税部月度考核模版.xls')
  } catch {
    message.error('模板下载失败')
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script> 